package my.support;

import my.dao.daoImpl.BookDao;
import my.dao.daoImpl.BookTypeDao;
import my.vo.voImpl.Book;
import my.vo.voImpl.User;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 星环
 * @date 2022/11/1 16:35:46
 * @description 因为查书的代码重复很多，干脆写个BookViewer，提供Book的显示和通用查询
 */
public class BookViewer {
    private final BookDao bookDao = BookDao.getInstance();
    //用于多表查询（）
    private final BookTypeDao bookTypeDao = BookTypeDao.getInstance();

    private final StringBuilder sb = new StringBuilder();

    private final User user;

    public BookViewer(User user) {
        this.user = user;
    }

    /**
     * 显示类别为 1. 类别  2.类别  5.类别   6.类别 。。。<br/>
     * 方便看
     */
    public void showTypeOptionList(){
        bookTypeDao.getAll().forEach(bookType -> System.out.print(bookType.getId() + "."+bookType.getName() + "\t"));
    }

    /**
     * 显示所有书，按格式，并且按名字显示类别
     */
    public void showAllBooks(){
        List<Book> books = bookDao.getAll();
        formatAndShowBooks(books);
    }

    /**
     * 传入类别名字，显示这类的书
     * @param btName
     */
    public void showBooksByBookTypeName(String btName){
        List<Integer> btIds = bookTypeDao.getIdByName(btName);
        if(btIds.size() == 0){
            System.out.println("没有这个类别");
            return;
        }
        List<Book> res = bookDao.getBooksByTypeIds(btIds);
        formatAndShowBooks(res);
    }

    /**
     * 提供一些书，按格式输出，并替换类别名
     * @param books 要显示的书
     */
    public void formatAndShowBooks(List<Book> books){
        Map<Integer,String> typeIdNameMap = new HashMap<>();
        //先把每种类别都按<id,name>的方式存入map
        bookTypeDao.getAll().forEach(bookType -> typeIdNameMap.put(bookType.getId(),bookType.getName()));
        //这样取得很快
        books.forEach(book -> {
            String typeName = typeIdNameMap.get(book.getTypeId());
            System.out.println(getBookDesc(book,typeName));
        });
    }

    private String getBookDesc(Book book, String typeName) {
        sb.setLength(0);
        sb.append("编号： ").
                append(book.getId()).
                append("类别： ").append(typeName).
                append("书名： ").append(book.getName()).
                append("作者： ").append(book.getAuthor()).
                append("出版社： ").append(book.getPublishingHouse());
        if(book.getBorrowerId() == 0){
            sb.append("可借");
        }else if (book.getBorrowerId() != user.getId()){
            sb.append("已被他人借走");
        }else {
            sb.append("您已借本书");
        }
        return sb.toString();
    }

    /**
     * 显示一本书
     * @param book
     */
    public void formatAndShowOneBook(Book book){
        String typeName = bookTypeDao.getById(book.getTypeId()).getName();
        System.out.println(getBookDesc(book,typeName));
    }
}
